from copy import deepcopy

from bs4 import BeautifulSoup
import json
import re

machine_map = {
    "采集机": "采集机",
    "采集器": "采集器",
    "采集器（白）": "采集器（白）",
    "采集器（绿）": "采集器（绿）",
    "采集器（蓝）": "采集器（蓝）",
    "采集器（紫）": "采集器（紫）",
    "采集器（橙）": "采集器（橙）",
}

def parse_receipts2(html):
    soup = BeautifulSoup(html, "html.parser")

    # 找到箭头部分
    arrow = soup.find("span", class_="formula-arrow")
    time_text = arrow.find("span", class_="formula-arrow-time").get_text(strip=True)
    device_find = arrow.find_all(class_=['formula-arrow-device', 'formula-arrow-device-white'])
    for e in device_find:
        device = e.get_text(strip=True)
        break

    # 提取时间数字（去掉 s）
    time_val = float(re.sub(r'[^0-9\.]', '', time_text))

    # 找到所有原料和产物
    icons = soup.find_all("span", class_="icon-background")

    # 箭头在第几个位置
    arrow_index = list(arrow.parent.children).index(arrow)

    # 分成 原料组 + 产物组
    materials = []
    products = []

    for icon in icons:
        name = icon.find("a")["title"]
        mount = int(icon.find("span", class_="icon-num").get_text())
        # 判断在箭头前还是后
        if icon.sourcepos < arrow.sourcepos:
            materials.append({"name": name, "mount": mount})
        else:
            products.append({"name": name, "mount": mount})

    # 多产物支持
    products_map = {}
    for product in products:
        products_map[product["name"]] = product
    result_arr = []
    for product in products_map:
        extra_product = deepcopy(products_map)
        extra_product.pop(product)
        result_arr.append({
            "name": product,
            "needs": materials,
            "time": time_val,
            "mount": products_map[product]["mount"],
            "machine": device,
            "extra": extra_product
        })

    print(json.dumps(result_arr, ensure_ascii=False, indent=2))
    return result_arr

def parse_origin(html: str) -> str:
    """
    在HTML中查找 <th>采集自</th> 后对应的 <td> 内容。
    若找到多个 <th>采集自</th>，抛出 ValueError。
    """
    soup = BeautifulSoup(html, "html.parser")

    # 找到所有 <th> 且文本精确为“采集自”的标签
    th_tags = [th for th in soup.find_all("th") if th.get_text(strip=True) == "采集自"]

    if len(th_tags) == 0:
        return None
    elif len(th_tags) > 1:
        raise ValueError("HTML中存在多个 <th>采集自</th> 标签！")

    th_tag = th_tags[0]
    td_tag = th_tag.find_next_sibling("td")
    if not td_tag:
        return None

    return td_tag.get_text(strip=True)

if __name__ == '__main__':
    xx = """<div class="item-info">
<p><span class="icon-background icon-big"><img alt="临界光子" src="https://patchwiki.biligame.com/images/dsp/thumb/9/96/sdzkuns1pfvmetxu9hqif50ngwvm805.png/70px-%E4%B8%B4%E7%95%8C%E5%85%89%E5%AD%90.png" decoding="async" loading="lazy" title="临界光子" width="70" height="70" srcset="https://patchwiki.biligame.com/images/dsp/9/96/sdzkuns1pfvmetxu9hqif50ngwvm805.png 1.5x" data-file-width="80" data-file-height="80"></span>
</p>
<p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><p><br>
</p><table class="item-table">
<tbody><tr><th>别称</th><td>光子</td></tr>
<tr><th>采集自</th><td>戴森云、戴森球</td></tr>
<tr><th>采集设备</th><td>射线接收站</td></tr>
<tr><th>手动采集</th><td>不可手动采集</td></tr>

<tr><th>潜在能量</th><td>1.2 GJ</td></tr>

<tr><th>堆叠上限</th><td>100/格</td></tr>
<tr><th>前置科技</th><td><span class="icon-background icon-small"><a href="/dsp/%E7%8B%84%E6%8B%89%E5%85%8B%E9%80%86%E5%8F%98%E6%9C%BA%E5%88%B6" title="狄拉克逆变机制"><img alt="狄拉克逆变机制" src="https://patchwiki.biligame.com/images/dsp/thumb/f/f7/6eaozz6ayqfccrnlu89karll7fefpf0.png/24px-%E7%8B%84%E6%8B%89%E5%85%8B%E9%80%86%E5%8F%98%E6%9C%BA%E5%88%B6.png" decoding="async" loading="lazy" width="24" height="24" srcset="https://patchwiki.biligame.com/images/dsp/thumb/f/f7/6eaozz6ayqfccrnlu89karll7fefpf0.png/36px-%E7%8B%84%E6%8B%89%E5%85%8B%E9%80%86%E5%8F%98%E6%9C%BA%E5%88%B6.png 1.5x, https://patchwiki.biligame.com/images/dsp/thumb/f/f7/6eaozz6ayqfccrnlu89karll7fefpf0.png/48px-%E7%8B%84%E6%8B%89%E5%85%8B%E9%80%86%E5%8F%98%E6%9C%BA%E5%88%B6.png 2x" data-file-width="80" data-file-height="80"></a></span><a href="/dsp/%E7%8B%84%E6%8B%89%E5%85%8B%E9%80%86%E5%8F%98%E6%9C%BA%E5%88%B6" title="狄拉克逆变机制">狄拉克逆变机制</a></td></tr>

<tr><td></td></tr></tbody></table></div>"""
    res = parse_origin(xx)
    print(f"解析结果:{res}")